package com.topscomm.mms;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.IBasicService;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.cbo.pojo.CboRoleEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.pojo.CboUserRoleEntity;
import com.topscomm.cbo.service.impl.CboRoleService;
import com.topscomm.cbo.service.impl.CboUserRoleService;
import com.topscomm.cbo.service.impl.CboUserService;
import com.topscomm.mis.MisService;
import com.topscomm.mms.IMmsDao;
import com.topscomm.mms.IMmsService;
import com.topscomm.mms.MmsEntity;
import com.topscomm.mms.pojo.MmsDeptExtraInfoEntity;
import com.topscomm.mms.pojo.MmsPostAuthorizationInfoEntity;
import com.topscomm.mms.service.impl.MmsDeptExtraInfoService;
import com.topscomm.mms.service.impl.MmsProvinceCityMatchinfoService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.TapService;
import com.topscomm.tap.common.DatacodeCache;
import com.topscomm.tap.common.RedisMmsStore;
import com.topscomm.tap.common.SessionUserBean;
import com.topscomm.tap.util.ErrorLogUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@SuppressWarnings("rawtypes")
public class MmsService<T extends MmsEntity, TDao extends IMmsDao> extends MisService<T, TDao> implements IMmsService<T, TDao> {
    @Autowired
    private MmsDeptExtraInfoService mmsDeptExtraInfoService;
    @Autowired
    private MmsProvinceCityMatchinfoService mmsProvinceCityMatchinfoService;
    @Autowired
    private RedisMmsStore redisMmsStore;
    @Autowired
	private AmqpTemplate rabbitTemplate;
    @Autowired
    private DatacodeCache datacodeCache;
    @Autowired
	private CboRoleService cboRoleService;
	@Autowired
	private CboUserRoleService cboUserRoleService;
	@Autowired
	private CboUserService cboUserService;

    @Override
    protected void afterSubmit(TapEntity entity, SessionUserBean sessionUserBean) {
        try {
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendLineSingle("update CboApprovalFlowIns set ");
            sql.appendLineSingle("extendfield1 = (select docno from {0} "
                            + "where CboApprovalFlowIns.sourceid = {0}.id " + "and CboApprovalFlowIns.sourcetype = '{0}'),",
                    entity.getTableName());
            sql.appendLineSingle("extendfield2 = (select deptcode from {0} "
                            + "where CboApprovalFlowIns.sourceid = {0}.id " + "and CboApprovalFlowIns.sourcetype = '{0}'),",
                    entity.getTableName());
            sql.appendLineSingle("extendfield3 = (select usercode from {0} "
                            + "where CboApprovalFlowIns.sourceid = {0}.id " + "and CboApprovalFlowIns.sourcetype = '{0}')",
                    entity.getTableName());
            sql.appendLineSingle("where sourceid = '{0}' and sourcetype='{1}'", entity.getId(), entity.getTableName());

            this.getDao().updateExecute(sql.toString());
        } catch (Exception e) {
            throw new ServiceException(e);
        }
		super.afterSubmit(entity, sessionUserBean);
    }
    /**
     * @description:获取省份信息Entity
     * @param deptCode
     * @return
     * @author: jiangtao1
     * @date: 2021年3月9日下午4:42:48
     * @modify:
     */
    public MmsDeptExtraInfoEntity getDeptCommonCodeEntity(String deptCode) {
        String firstdeptcode = this.getSubStringFirstDeptCode(deptCode);
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendLineSingle(" concat(',',concat("+ MmsDeptExtraInfoEntity.FieldDeptcode+",',')) like '%,{0},%' ", firstdeptcode);
        return  mmsDeptExtraInfoService.queryObjectByWhere(sql.toString());
    }

    /**
     * @description:获取省份信息编码
     * @param deptCode
     * @return
     * @author: jiangtao1
     * @date: 2021年3月9日下午4:42:48
     * @modify:
     */
    public String getDeptCommonCode(String deptCode) {
        String firstdeptcode = this.getSubStringFirstDeptCode(deptCode);
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendLineSingle(" concat(',',concat("+ MmsDeptExtraInfoEntity.FieldDeptcode+",',')) like '%,{0},%' ", firstdeptcode);
        MmsDeptExtraInfoEntity mmsDeptExtraInfoEntity = mmsDeptExtraInfoService.queryObjectByWhere(sql.toString());
        String deptCommonCode = null;
        if (mmsDeptExtraInfoEntity != null) {
            deptCommonCode = mmsDeptExtraInfoEntity.getDeptcommoncode();
        }
        return deptCommonCode;
    }

    /**
     * @description: 根据编码截取一级部门编码
     * @param deptCode
     * @return java.lang.String
     * @author: wangxinhua
     * @date: 2021/7/7 14:47
     * @modify:
     */
    public String getSubStringFirstDeptCode(String deptCode) {
        if(deptCode.contains("_")) {
            List<String> codeSplit = Arrays.asList(deptCode.split("_"));
            if(codeSplit.get(1).length() > 4){
                codeSplit.set(1, codeSplit.get(1).substring(0,4));
                return StringUtils.join(codeSplit, "_");
            } else {
                return deptCode;
            }
        }else {
            if(deptCode.length()>4) {
                return deptCode.substring(0, 4);
            }else {
                return deptCode;
            }
        }
    }


    /**
     *
     * @description: 判断是否为运营人员
     * @return
     * @author: hudeyong
     * @date: 2021-06-24
     * @modify:
     */
    public Boolean checkIsOperators() {
        boolean key = false;
        Map<String, Object> paraMap = new HashMap<String, Object>();
        paraMap.put("code", MmsSystemConst.ItemsEnum.bspOperators);
        paraMap.put("usercode", getSessionUserBean().getUser().getCode());
        int count = mmsProvinceCityMatchinfoService.getCount(paraMap, "getOperatorsCount");
        if(count>0) {
            return true;
        }
        return key;
    }

    /**
     * @description: 新增、更新、删除后存redis
     * @return void
     * @author: wangxinhua
     * @date: 2021/8/6 16:29
     * @modify:
     */
    public void addValueToRedis(String tableName) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String serviceName = (new StringBuilder()).append(Character.toLowerCase(tableName.charAt(0))).append(tableName.substring(1)).append("Service").toString();
                    //查所有存redis
                    IBasicService iBasicService;
                    iBasicService = (IBasicService) SpringUtil.getBean(serviceName);
                    List<Map<String,Object>> allData = iBasicService.queryMapByWhere(" 1=1 ");
                    redisMmsStore.storeData(tableName, allData);
                } catch (Exception e) {
                    ErrorLogUtil.writeLogAndSendMessage(e);
                    e.printStackTrace();
                }
            }
        }).start();
    }
    /**
     * @description: 给fds发生消息队列，用于更新或新增角色
     * @return void
     * @author: hdy
     * @date: 2022/11/10 16:29
     * @modify:
     */
    @Override
    public void sendMessageToFds(Map<String, Object> map, String tableName) {
    	Map<String, Object> sendMap = new HashMap<>();
    	String code = "permission";
    	String name = "";
    	String usercode = "";
    	String deptcommoncode = "";
    	String type = "";
    	if(tableName.equals(MmsDeptExtraInfoEntity.tableName)) {
    		type = MmsDeptExtraInfoEntity.tableName;
    		deptcommoncode = ConvertUtil.convertToString(map.get("deptcommoncode"));
    		code = code + "Province" + deptcommoncode;
    		name = datacodeCache.getValueDynamic("DeptCommonCode", deptcommoncode, "code", "name")+"(省区)";
    		if(!ConvertUtil.convertToString(map.get("provincemanagercode")).isEmpty()) {
    			usercode = ConvertUtil.convertToString(map.get("provincemanagercode"));
    		}
    		if(!ConvertUtil.convertToString(map.get("cfocode")).isEmpty()) {
    			usercode = usercode.isEmpty() ? ConvertUtil.convertToString(map.get("cfocode"))
    					: (usercode + "," + ConvertUtil.convertToString(map.get("cfocode")));
    		} else {
    			return;
    		}
    		sendMap.put("deptcommoncode", deptcommoncode);
        	sendMap.put("code", code);
    		sendMap.put("name", name);
    		sendMap.put("usercode", usercode);
    	} else if(tableName.equals(MmsPostAuthorizationInfoEntity.tableName)){
    		String postcode = ConvertUtil.convertToString(map.get("postcode"));
    		if(!postcode.equals("2") && !postcode.equals("3")) {
    			return;
    		}
    		type = MmsPostAuthorizationInfoEntity.tableName;
    		deptcommoncode = ConvertUtil.convertToString(map.get("deptcommoncode"));
    		code = code + "Productline" + deptcommoncode;
    		name = datacodeCache.getValueDynamic("PostDeptCommonCode", deptcommoncode, "code", "name")+"(产品线)";
    		if(!ConvertUtil.convertToString(map.get("usercode")).isEmpty()) {
    			usercode = ConvertUtil.convertToString(map.get("usercode"));
    		} else {
    			return;
    		}
    		sendMap.put("deptcommoncode", deptcommoncode);
        	sendMap.put("code", code);
    		sendMap.put("name", name);
    		sendMap.put("usercode", usercode);
    	} else if(tableName.equals("specialRoles")){
    		type = "specialRoles";
    		sendMap.putAll(map);
    	} else {
    		return;
    	}
    	sendMap.put("type", type);
		JSONObject json = new JSONObject(sendMap);
		solveRoleMessage(json.toJSONString());
		this.rabbitTemplate.convertAndSend("fdsRoleQueue",json.toJSONString());
    }

    /**
	 * 接收BSP修改部门扩展/岗位授权表发送的消息
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: hdy
	 * @date: 2022/11/10
	 * @modify:
	 */
	public void solveRoleMessage(String msg) {
		// 接收到的消息
		Map<String,Object> message = JSONObject.parseObject(msg);
		StringBufferProxy sql = new StringBufferProxy();
		// 传来的编号、名称、人员工号
		String code = ConvertUtil.convertToString(message.get("code"));
		String name = ConvertUtil.convertToString(message.get("name"));
		String usercodes = ConvertUtil.convertToString(message.get("usercode"));
		sql.clear();
		sql.appendSingle("code = '{0}'", code);
		List<CboRoleEntity> roleEntities = cboRoleService.queryByWhere(sql.toString());
		if(roleEntities.size()>0) {
			//更新
			updateRole(roleEntities, code, name, usercodes);
		} else {
			//新增角色
			insertRole(code, name, usercodes);
		}
	}

	/**
	 *
	 * @description:更新角色
	 * @param paraMap
	 * @return
	 * @author: hdy
	 * @date: 2022/11/14
	 * @modify:
	 */
	public void updateRole(List<CboRoleEntity> roleEntities,String code, String name, String userCodes)  {
		CboRoleEntity cboRoleEntity = new CboRoleEntity();
		CboUserRoleEntity cbouserRoleEntity = new CboUserRoleEntity();
		long roleid = ConvertUtil.convertToLong(roleEntities.get(0).getId());
		cboRoleEntity = roleEntities.get(0);
		cboRoleEntity.setName(name);
		cboRoleEntity.setCode(code);
		cboRoleService.updateEntity(cboRoleEntity);
		StringBufferProxy sql = new StringBufferProxy();
		sql.clear();
		sql.appendSingle("roleid = '{0}'", roleid);
		cboUserRoleService.deleteByWhere(sql.toString());
		String[] usercodeList = userCodes.split(",");
		for(String usercode : usercodeList) {
			sql.clear();
			sql.appendSingle("code = '{0}'", usercode);
			List<CboUserEntity> cboUserEntities = cboUserService.queryByWhere(sql.toString());
			if(cboUserEntities.size()>0) {
				cbouserRoleEntity = new CboUserRoleEntity();
				cbouserRoleEntity.setRoleid(roleid);
				cbouserRoleEntity.setUserid(cboUserEntities.get(0).getId());
				cboUserRoleService.insert(cbouserRoleEntity);
			}
		}
	}

	/**
	 *
	 * @description:新增角色
	 * @param paraMap
	 * @return
	 * @author: hdy
	 * @date: 2022/11/14
	 * @modify:
	 */
	public void insertRole(String code, String name, String userCodes)  {
		CboRoleEntity cboRoleEntity = new CboRoleEntity();
		long[] roleid = PrimaryKeyUtil.GeneIDs(cboRoleEntity.tableName, 1);
		cboRoleEntity.setId(roleid[0]);
		cboRoleEntity.setCode(code);
		cboRoleEntity.setName(name);
		cboRoleService.insert(cboRoleEntity);
		//新增角色人员
		String[] usercodeList = userCodes.split(",");
		StringBufferProxy sql = new StringBufferProxy();
		for(String usercode : usercodeList) {
			CboUserRoleEntity cbouserRoleEntity = new CboUserRoleEntity();
			sql.clear();
			sql.appendSingle("code = '{0}'", usercode);
			List<CboUserEntity> cboUserEntities = cboUserService.queryByWhere(sql.toString());
			if(cboUserEntities.size()>0) {
				cbouserRoleEntity = new CboUserRoleEntity();
				cbouserRoleEntity.setRoleid(roleid[0]);
				cbouserRoleEntity.setUserid(cboUserEntities.get(0).getId());
				cboUserRoleService.insert(cbouserRoleEntity);
			}
		}
	}
}
